var app = getApp();
Page({
  data: {
    code:'',
  },
  goBack: function () {
    wx.switchTab({
      url: '/pages/personalCenter1/index',
    })
  },
  onShow: function () {
    let self = this
    wx.login({
      success: function (res) {
        console.log(res)
        if (res.code) {
          console.log(res.code)
          self.setData({
            code: res.code
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  registlogin(){
    let self = this
    wx.getUserInfo({
      withCredentials: true,
      success: res => {
      app.request({
        url: 'api/Wechat/getWeChatMiniUserByCode',
        data: {
          encryptedData: res.encryptedData,
          iv: res.iv,
          code: self.data.code
        },
        method: "get",
        success: function (data, header) {
          wx.hideLoading()
          console.log(data)
          if (data.data && data.data.result) {
            app.globalData.AlreadyJumpedLogin = true;
              console.log(header["Set-Cookie"])
              // var index1 = header["Set-Cookie"].indexOf("wechatAuthTokenV2")
              // var index2 = header["Set-Cookie"].indexOf(";", index1)
              // var cookie = header["Set-Cookie"].substring(index1, index2)

              var usernameKey = "DisplayUserName"
              var index3 = header["Set-Cookie"].indexOf(usernameKey) + usernameKey.length + 1
              var index4 = header["Set-Cookie"].indexOf(";", index3)
              var username = header["Set-Cookie"].substring(index3, index4)
              wx.setStorageSync('cookie', header["Set-Cookie"])
              wx.setStorageSync('username', username)
              console.log(data.data.info)
              wx.switchTab({
                url: '/pages/personalCenter1/index',
              })
          }
        },
        fail:function(){
          wx.showToast({ title: "请再试一次", icon: "none", duration: 2000 })
        }
      })

  }
})
  },
  bindGetUserInfo: function (e) {
    let that = this;
    //用户按了允许授权按钮
    if (e.detail.userInfo) {
      that.registlogin()
    } else {
      wx.showToast({ title: "授权失败，请重试", icon: "none", duration: 2000 })
    }
  },
  getPhoneNumber: function (e) {
    var that = this;
        console.log(e.detail.errMsg);
        if (e.detail.errMsg == "getPhoneNumber:ok") {
              that.registlogin()
        }
        else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') { //拒绝授权
          wx.showToast({
            title: '您拒绝了授权',
            icon: 'none',
            duration: 2000
          })

        } else if (e.detail.errMsg === 'getPhoneNumber:fail 用户未绑定手机，请先在微信客户端进行绑定后重试') {
          wx.showToast({
            title: '您的微信未绑定手机号',
            icon: 'none',
            duration: 3000
          })
        }
      
  }
})